package servlets;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Adresse;
import model.Termin;
import service.TerminplanerConnectionPool;
import service.TerminplanerService;
import service.TokenStore;

@WebServlet("/EditTerminServlet")
public class EditTerminServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    request.getSession().setAttribute("token", TokenStore.getInstance().createToken());
    Connection con = null;
    Long terminId = null;
    Termin termin = null;
    Adresse adresse = null;
    try {
      terminId = Long.valueOf(request.getParameter("TerminId"));
      con = TerminplanerConnectionPool.getInstanz().getConnection();
      termin = TerminplanerService.getInstanz().getTermin(con, terminId);
      adresse = TerminplanerService.getInstanz().getAdresseByTerminId(con, terminId);

    } catch (Exception e) {
      request.setAttribute("exception", e.getMessage());
      request.getRequestDispatcher("/WEB-INF/jsps/error.jsp").forward(request, response);
      e.printStackTrace();
      return;
    } finally {
      TerminplanerConnectionPool.getInstanz().saveClose(con);
    }

    request.setAttribute("thema", termin.getThema());
    request.setAttribute("terminanfang", termin.getFormattedTerminAnfang());
    request.setAttribute("terminende", termin.getFormattedTerminEnde());
    request.setAttribute("terminart", termin.getTerminArt());
    request.setAttribute("prioritaet", termin.getPrioritaet());
    request.setAttribute("strasse", adresse.getStrasse());
    request.setAttribute("plz", adresse.getPlz());
    request.setAttribute("ort", adresse.getOrt());
    request.setAttribute("land", adresse.getLand());
    request.setAttribute("beschreibung", termin.getBeschreibung());
    request.setAttribute("terminid", terminId);

    request.getRequestDispatcher("/WEB-INF/jsps/addTermin.jsp").forward(request, response);
  }

}
